package com.corecloud.controller.sys;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.corecloud.controller.sms.SmsCode;
import com.corecloud.controller.sms.SmsCodeFilter;
import com.corecloud.entity.SysPermissionEntity;
import com.corecloud.entity.SysUserEntity;
import com.corecloud.service.OtherBaseService;
import com.corecloud.service.SysPermissionService;
import com.corecloud.service.SysUserService;
import com.corecloud.service.sms.ValidateCodeProcessor;
import com.corecloud.tools.AjaxResultData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 首页相关
 */
@Controller
public class HomeController {

	@Autowired
	private AuthenticationFailureHandler authenticationFailureHandler;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysPermissionService sysPermissionService;
	@Autowired
	private OtherBaseService otherBaseService;
	@Autowired
	private SmsCodeFilter smsCodeFilter;

	/**
	 * 跳转回移动登录页
	 * @return
	 */
	@RequestMapping("/h5SignIn/index")
	public String h5SignInHome(){
		return "logs/indexH5";
	}
	/**
	 * 跳转移动实名认证页面
	 * @return
	 */
	@RequestMapping("/h5SignIn/verified")
	public ModelAndView h5SignInAuthenti(String id){
		SysUserEntity sysUserEntity = new SysUserEntity();
		sysUserEntity.setId(Integer.valueOf(id));
		ModelAndView modelAndView = new ModelAndView("logs/authenticationH5");
		modelAndView.addObject("personalInFormation", sysUserEntity);
		return modelAndView;
	}
	/**
	 * 跳转PC实名认证页面
	 * @return
	 */
	@RequestMapping("/h5SignIn/pcverified")
	public ModelAndView psSignInAuthenti(String id){
		SysUserEntity sysUserEntity = new SysUserEntity();
		sysUserEntity.setId(Integer.valueOf(id));
		ModelAndView modelAndView = new ModelAndView("logs/authenticationPc");
		modelAndView.addObject("personalInFormation", sysUserEntity);
		return modelAndView;
	}

	/**
	 * 首页-密码登陆
	 * @return
	 */
	@RequestMapping({"/home/index","","/"})
	public ModelAndView index(Principal principal){
		String username = principal.getName();
		//获取详细用户信息并根据用户信息生成可访问菜单对应数据等进行展示
		SysUserEntity user = sysUserService.selectOne(new QueryWrapper<SysUserEntity>().eq("user_name",username));
		//获取权限合集用以生成首页菜单(暂支持两级结构,后期如增加多级菜单需修改逻辑)
		Map<String, Object> map = new HashMap<>();
		map.put("uid",user.getId());
		map.put("permissionType",0);

		ModelAndView modelAndView = new ModelAndView();
//		判断手机号与身份证号是否为空
		String id_card = user.getIdCard();
		String phone = user.getPhone();

//		取出一二级菜单
		List<SysPermissionEntity> permissionList = sysPermissionService.getListByUserParas(map);

		modelAndView.addObject("menuList",permissionList);
		modelAndView.addObject("userInfo",user);
		//用以登录学校学生管理信息系统
		modelAndView.addObject("USER_NAME", Base64.getEncoder().encodeToString(user.getUserName().getBytes()));
		if (StringUtils.isEmpty(id_card) || StringUtils.isEmpty(phone)){
			modelAndView.setViewName("logs/authenticationPc");
			modelAndView.addObject("personalInFormation",user);
		}else {
			//封装页面数据
			modelAndView.setViewName("home/index");
		}

		//获取快速入口等数据,存放在权限表，需要根据用户角色去获取可以访问的第三方接入平台
		map = new HashMap<>();
		map.put("uid",user.getId());
		map.put("permissionType",1);
		List<SysPermissionEntity> appList = sysPermissionService.getListByUserParas(map);
		modelAndView.addObject("appList",appList);
		return modelAndView;
	}

	/**
	 * 首页-验证码登陆
	 * @return
	 */
	@RequestMapping({"/home/index2","","/"})
	public ModelAndView index2(Principal principal){
		String username = principal.getName();
		//获取详细用户信息并根据用户信息生成可访问菜单对应数据等进行展示
		SysUserEntity user = sysUserService.selectOne(new QueryWrapper<SysUserEntity>().eq("phone",username));
		//获取权限合集用以生成首页菜单(暂支持两级结构,后期如增加多级菜单需修改逻辑)
		Map<String, Object> map = new HashMap<>();
		map.put("uid",user.getId());
		map.put("permissionType",0);
//		取出一二级菜单
		List<SysPermissionEntity> permissionList = sysPermissionService.getListByUserParas(map);
		//封装页面数据
		ModelAndView modelAndView = new ModelAndView("home/index");
		modelAndView.addObject("menuList",permissionList);
		modelAndView.addObject("userInfo",user);
		//用以登录学校学生管理信息系统
		modelAndView.addObject("USER_NAME", Base64.getEncoder().encodeToString(user.getUserName().getBytes()));

		//获取快速入口等数据,存放在权限表，需要根据用户角色去获取可以访问的第三方接入平台
		map = new HashMap<>();
		map.put("uid",user.getId());
		map.put("permissionType",1);
		List<SysPermissionEntity> appList = sysPermissionService.getListByUserParas(map);
		modelAndView.addObject("appList",appList);
		return modelAndView;
	}

	/**
	 * 首页-首页桌面(填充内容)
	 * @return
	 */
	@RequestMapping("/home/welcome")
	public ModelAndView welcome(Principal principal){
		//封装页面数据
		ModelAndView modelAndView = new ModelAndView("home/welcome");
		//当前登录用户信息
		SysUserEntity user = sysUserService.selectOne(new QueryWrapper<SysUserEntity>().eq("user_name",principal.getName()));
		//常用入口
		Map map = new HashMap<>();
		map.put("uid",user.getId());
		map.put("permissionType",1);
		List<SysPermissionEntity> appList = sysPermissionService.getListByUserParas(map);
		//页面设计原因，仅取六条进行展示
		if(appList != null && appList.size() > 6){
			appList = appList.subList(0,6);
		}
		modelAndView.addObject("appList",appList);
		//获取首页数据统计相关信息
		modelAndView.addObject("statisticsData",otherBaseService.getWelcomePageData());
		modelAndView.addObject("userInfo",user);
		//用以登录学校学生管理信息系统
		modelAndView.addObject("USER_NAME", Base64.getEncoder().encodeToString(user.getUserName().getBytes()));
		return modelAndView;
	}

	/**
	 * 跳转回首页-用以应对某些第三方平台设置的回调地址
	 * @return
	 */
	@RequestMapping("/usercenter/index")
	public String userCenterIndex(Principal principal){
		return "redirect:/";
	}

	/**
	 * 个人信息完善提交接口
	 * @return
	 */
	@RequestMapping("/improvePersonalInformation")
	@ResponseBody
	public AjaxResultData improvePersonalInformation(SysUserEntity info){
		String id = info.getId().toString();
		String name = info.getName();
		String idCard = info.getIdCard();
		String phone = info.getPhone();
		String codePhone = info.getCodePhone();

		if (StringUtils.isEmpty(id)){ return new AjaxResultData(500,"参数异常,请联系管理员"); }
		if (StringUtils.isEmpty(idCard)){ return new AjaxResultData(500,"请填写身份证号码"); }
		if (StringUtils.isEmpty(phone)){ return new AjaxResultData(500,"请填写手机号"); }
		if (StringUtils.isEmpty(codePhone)){ return new AjaxResultData(500,"请填写验证码"); }

		SysUserEntity sysUserEntityIdCard = selectOne("id_card", idCard);
		if (!StringUtils.isEmpty(sysUserEntityIdCard)){ return new AjaxResultData(500,"该身份证号已被占用"); }

		SysUserEntity sysUserEntityPhone = selectOne("phone", phone);
		if (!StringUtils.isEmpty(sysUserEntityPhone)){ return new AjaxResultData(500,"该手机号已被占用"); }
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

		//设置用户需要比对的密码
		SmsCode smsCode = (SmsCode)request.getSession().getAttribute(ValidateCodeProcessor.SESSION_KEY_PREFIX + phone);
 		if (!codePhone.equals(smsCode.getCode())){ return new AjaxResultData(500,"验证码有误请重新获取"); }
 		if (smsCode.getCode() == null){ return new AjaxResultData(500,"验证码不存在"); }
		if (smsCode.isExpired()) { return new AjaxResultData(500,"短信验证码已过期"); }
		if(!codePhone.equalsIgnoreCase(smsCode.getCode())) { return new AjaxResultData(500,"短信验证码错误"); }
		if(!smsCode.getMobile().equals(phone)) { return new AjaxResultData(500,"输入的手机号与发送短信验证码的手机号不一致"); }

//		查询该用户信息
		SysUserEntity sysUserEntityS = selectOne("id", id);

		//数据录入
		try {
			//重置机构信息
			sysUserEntityS.setIdCard(idCard.trim());
			sysUserEntityS.setPhone(phone.trim());
			sysUserEntityS.setName(name.trim());
			sysUserService.updateInfo(sysUserEntityS);
			return new AjaxResultData(200,"操作成功");
		} catch (Exception e){
			return new AjaxResultData(500,"操作失败,请联系管理员");
		}
	}

	/**
	 * 查询用户单个数据
	 * @param name：要查询的字段
	 * @param value：查询的数据
	 * @return
	 */
	public SysUserEntity selectOne(String name, String value){
		return sysUserService.selectOne(new QueryWrapper<SysUserEntity>().eq(name, value));
	}
}
